﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using YiSha.Core.DynamicData;

namespace YiSha.Admin.Web.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class DynamicController : ControllerBase
    {
        private readonly IFreeSql _db;
        private readonly ICacheEntity _cacheEntity;
        public DynamicController(ICacheEntity cacheEntity, IFreeSql db)
        {
            _cacheEntity = cacheEntity;
            _db = db;
        }
        [HttpPost("Create/{MenuId}")]
        public IActionResult Create([FromRoute] int MenuId, [FromBody] Dictionary<string, object> entity)
        {
            var table = _cacheEntity.GetOriginalTable(MenuId);
            if (entity.ContainsKey("Id"))
            {
                entity["Id"] = IdGeneratorHelper.Instance.GetId();
            }
            _db.InsertDict(entity).AsTable(table.TableName).ExecuteInserted();
            return Ok();
        }
        [HttpPost("Modify/{MenuId}/{Id}")]
        public IActionResult Modify([FromRoute] int MenuId, [FromRoute] string Id, [FromBody] Dictionary<string, object> entity)
        {
            var table = _cacheEntity.GetOriginalTable(MenuId);

            _db.UpdateDict(entity).WherePrimary("Id").AsTable(table.TableName).ExecuteUpdated();
            return Ok();
        }
        [HttpPost("Delete/{MenuId}/{Id}")]
        public IActionResult Delete([FromRoute] int MenuId, [FromRoute] string Id)
        {
            var table = _cacheEntity.GetOriginalTable(MenuId);
            var dic = new Dictionary<string, object>();
            dic.Add("Id", Id);
            _db.DeleteDict(dic).AsTable(table.TableName).ExecuteAffrows();
            return Ok();
        }
        [HttpGet("{MenuId}/{Id}")]
        public IActionResult Get([FromRoute] int MenuId, [FromRoute] string Id)
        {
            var table = _cacheEntity.GetOriginalTable(MenuId);
            var items = _db.Select<dynamic>().AsTable((type, old) => table.TableName).Where("Id=" + Id).ToList();
            return Ok(items);
        }
        [HttpPost("Paged/{MenuId}")]
        public IActionResult Paged([FromRoute] int MenuId)
        {
            var table = _cacheEntity.GetOriginalTable(MenuId);
            var items = _db.Select<dynamic>().AsTable((type, old) => table.TableName).Page(1, 3).ToList();
            return Ok(items);
        }
    }
}
